package uit.mmt02.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import uit.mmt02.R;
import uit.mmt02.adapter.FileArrayAdapter;
import uit.mmt02.doituong.Option;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ListView;

public class FileDialog_OpenActivity extends ListActivity {
	/** Called when the activity is first created. */
	// Button bOpenDialog;
	File currentDir;
	FileArrayAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.file_view);
		// bOpenDialog = (Button)findViewById(R.id.bOpentDialog);

		//currentDir = new File("/sdcard/");
		currentDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
		fill(currentDir);
	}

	public void fill(File f) {

		File[] dirs = f.listFiles();

		this.setTitle("Current Dir: " + f.getName());

		List<Option> dir = new ArrayList<Option>();

		List<Option> fls = new ArrayList<Option>();

		try {

			for (File ff : dirs)

			{

				if (ff.isDirectory())

					dir.add(new Option(ff.getName(), "Folder", ff.getAbsolutePath()));

				else

				{

					fls.add(new Option(ff.getName(), "File Size: "+ ff.length(), ff.getAbsolutePath()));

				}

			}

		} catch (Exception e)

		{

		}

		Collections.sort(dir);

		Collections.sort(fls);

		dir.addAll(fls);

		if (!f.getName().equalsIgnoreCase("sdcard"))

			dir.add(0, new Option("..", "Parent Directory", f.getParent()));

		adapter = new FileArrayAdapter(FileDialog_OpenActivity.this, R.layout.file_view, dir);

		this.setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Option o = adapter.getItem(position);

		if (o.getData().equalsIgnoreCase("folder")|| o.getData().equalsIgnoreCase("parent directory")) {

			currentDir = new File(o.getPath());

			fill(currentDir);

		} else {
			onFileClick(o);
		}

	}

	private void onFileClick(Option o)

	{

		Intent in = new Intent();
		in.setData(Uri.parse(o.getPath()));
		//in.setData(Uri.parse("THAI THI THU THAO"));
		
		setResult(RESULT_OK, in);
		
		//Toast.makeText(this, "File Clicked: " + o.getName()+"\nPath: "+o.getPath(), Toast.LENGTH_SHORT).show();
		
		finish();

	}

}